package com.yangyang.androidconnect.common;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Build;

import org.greenrobot.eventbus.EventBus;

// NetworkMonitor.java
public class NetworkMonitor {
    private final Context context;
    private final NetworkCallback networkCallback;

    public NetworkMonitor(Context context) {
        this.context = context.getApplicationContext();
        this.networkCallback = new NetworkCallback();
    }

    public void startMonitoring() {
        ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            cm.registerDefaultNetworkCallback(networkCallback);
        } else {
            NetworkRequest request = new NetworkRequest.Builder().build();
            cm.registerNetworkCallback(request, networkCallback);
        }
    }

    public void stopMonitoring() {
        ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
        cm.unregisterNetworkCallback(networkCallback);
    }

    private class NetworkCallback extends ConnectivityManager.NetworkCallback {
        @Override
        public void onAvailable(Network network) {
            // 网络连接变化时触发IP更新
            EventBus.getDefault().post(new NetworkChangeEvent());
        }
    }

    public static class NetworkChangeEvent {} // 事件类
}